<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/10/25
 * Time: 11:32
 */
namespace App\Http\Controllers\web;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Module\EntPosterTemplate;
use App\Module\EntMemberInfo;
use App\Module\EntMemberDRP;
use App\Module\EntPushMoneyLog;
use App\Module\EntPayCard;
use App\Module\EntMobileCode;
use App\Module\EntWithdrawMoneyLog;
use Session;
use Redirect, Validator, Cookie, Response, DB;

class AgencyController extends Controller
{
    protected $scaleOne = '0.3';
    protected $scaleTwo = '0.05';
    protected $scaleMoney = '2000';
    protected $arrayBank = ['中国农业银行', '中国邮政银行', '中国建设银行', '中国交通银行', '中国工商银行'];
    protected $address = ['陈亮', '上海市徐汇区龙漕路299号天华信息科技园3B楼8层'];

    public function index()
    {
        //  Session::put('MName', '13761325105');
        // Session::put('MKey', 'b6d7606fbcebaa1b47bd9dda5fe11c20');
        $url = 'http://wx.laohoulundao.com/qrcode.html';
        $nonceStr = str_random(16);
        $timeStamp = $this->timeStamp();
        $appId = env('WEIXIN_APPID');
        $accessToken = $this->accessToken();
        $ticket = '';
        if ($accessToken != '') {
            $ticket = $this->ticket($accessToken);
        }
        $arrayWXShare = ['noncestr' => $nonceStr, 'timestamp' => $timeStamp, 'jsapi_ticket' => $ticket, 'url' => $url];
        $signature = $this->signature($arrayWXShare);
        $wxShare = ['appId' => $appId, 'nonceStr' => $nonceStr, 'timeStamp' => $timeStamp, 'signature' => $signature];
        $entPosterTemplate = EntPosterTemplate::select('PosterTitle', 'FilePath1', 'PoTeID')->where('DeleteMark', 1)->where('IsShow', 1)->orderBy('ReleaseDate', 'desc')->get();
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $defaultImg = '';
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        if (count($memberInfo) > 0) {
            $tempimg = $_SERVER['DOCUMENT_ROOT'] . '/uploads/posttemp/' . $memberInfo->MemNumber . '.png';
            if (file_exists($tempimg)) {
                $defaultImg = '/uploads/posttemp/' . $memberInfo->MemNumber . '.png';
            } else {
                $defaultImg = $this->defaultShareimgStore();
            }
        }
        //$this->pushMoneyLogStore('2016100101492930408');
        $entMemberDRP = EntMemberDRP::select('DRPLevel')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', 1)->first();
        if (count($entMemberDRP) > 0) {
            if ($entMemberDRP->DRPLevel > 1) {
                return redirect('/partneralert.html');
            }
        } else {
            return redirect('/partneralert.html');
        }


        return view('partner.qrcode', ['entPosterTemplate' => $entPosterTemplate, 'wxShare' => $wxShare, 'memberInfo' => $memberInfo, 'defaultImg' => $defaultImg, 'tempimg' => $tempimg]);
    }

    public function shareimgstore(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $MName = Session::get('MName');
                $MKey = Session::get('MKey');
                $memberInfo = $this->checkMemberInfo($MName, $MKey);
                //会员标示
                $memNumber = $memberInfo->MemNumber;
                $id = $request->json('id');
                $mimg = $request->json('mimg');
                $qrimg = $request->json('qrimg');
                //海报模板
                $img1 = imageCreateFromPng($_SERVER['DOCUMENT_ROOT'] . $mimg);
                //会员二维码
                $img2 = imageCreateFromPng($_SERVER['DOCUMENT_ROOT'] . $qrimg);
                imagecopymerge($img1, $img2, 205, 400, 0, 0, imagesx($img2), imagesy($img2), 100);
                imagepng($img1, $_SERVER['DOCUMENT_ROOT'] . '/uploads/posttemp/' . $memNumber . '.png');
                imagedestroy($img1);
                $result = '/uploads/posttemp/' . $memNumber . '.png';

            }
        } catch (Exception $e) {
            $result = '';
        }
        return $result;
    }

    /**返回默认模板
     * @return string
     */
    protected function defaultShareimgStore()
    {

        $url = '';
        try {
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            $memberInfo = $this->checkMemberInfo($MName, $MKey);
            //会员标示
            $memNumber = $memberInfo->MemNumber;
            //获取第一个模板
            $entPosterTemplate = EntPosterTemplate::select('PosterTitle', 'FilePath1', 'PoTeID')->where('DeleteMark', 1)->where('IsShow', 1)->orderBy('ReleaseDate', 'desc')->first();
            $FilePath1 = $entPosterTemplate->FilePath1;
            if ($memNumber != '' && $FilePath1 != '') {
                $mimg = $FilePath1;
                $qrimg = '/uploads/qrcode/' . $memNumber . '.png';
                //海报模板
                $img1 = imageCreateFromPng($_SERVER['DOCUMENT_ROOT'] . $mimg);
                //会员二维码
                $img2 = imageCreateFromPng($_SERVER['DOCUMENT_ROOT'] . $qrimg);
                imagecopymerge($img1, $img2, 205, 400, 0, 0, imagesx($img2), imagesy($img2), 100);
                imagepng($img1, $_SERVER['DOCUMENT_ROOT'] . '/uploads/posttemp/' . $memNumber . '.png');
                imagedestroy($img1);
                $url = '/uploads/posttemp/' . $memNumber . '.png';
            }
        } catch (Exception $e) {
            $url = '';
        }
        return $url;
    }

    /**返回JS-SDK权限验证签名
     * @param $array 签名数组
     * @return string
     */
    protected function signature($array)
    {
        /**
         * 生成JS-SDK权限验证签名
         * 注：签名不能包含空的值
         */
        $signStr = '';
        $arraySign = array_sort_recursive($array);

        foreach ($arraySign as $key => $val) {
            if ($val != '') {
                $signStr .= $key . '=' . $val . '&';
            }
        }
        $signStr = rtrim($signStr, '&');
        //strtoupper 把字符串转换为大写 strtolower--小写
        return sha1($signStr);

    }

    /**返回未过期Access_Token
     * @return \SimpleXMLElement[]|string
     */
    protected function accessToken()
    {
        $accessToken = '';
        if (file_exists('XMLFile.xml')) {
            $xml = simplexml_load_file('XMLFile.xml');
            $endAccessTime = $xml->Access_Time;
            if ($endAccessTime != '') {
                $zero1 = date('Y-m-d H:i:s');
                $zero2 = $endAccessTime;
                if (strtotime($zero1) < strtotime($zero2)) {
                    //未到期
                    $accessToken = $xml->Access_Token;
                } else {
                    //到期
                    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . env('WEIXIN_APPID') . '&secret=' . env('WEIXIN_APPSECRET') . '';
                    $responseText = $this->getHttpResponseGET($url);
                    if ($responseText != '') {
                        $jsonAccessToken = json_decode($responseText);
                        if ((array_key_exists('access_token', $jsonAccessToken))) {
                            $Token = $jsonAccessToken->access_token;
                            if ($Token != '') {
                                $xml->Access_Token = $Token;//修改节点
                                $xml->Access_Time = date('Y-m-d H:i:s', time() + 7200);
                                $xml->asXML('XMLFile.xml');
                                $accessToken = $Token;
                            } else {
                                $accessToken = 'no';
                            }
                        } else {
                            $accessToken = 'no';
                        }
                    } else {
                        $accessToken = 'no';
                    }
                }
            }
        }
        return $accessToken;
    }

    /**返回未过期的ticket
     * @param string $token
     * @return \SimpleXMLElement[]|string
     */
    protected function ticket($token = '')
    {
        $ticket = '';
        if (file_exists('XMLTicket.xml')) {
            $xml = simplexml_load_file('XMLTicket.xml');
            $endTicketTime = $xml->Ticket_Time;
            if ($endTicketTime != '') {
                $zero1 = date('Y-m-d H:i:s');
                $zero2 = $endTicketTime;
                if (strtotime($zero1) < strtotime($zero2)) {
                    //未到期
                    $ticket = $xml->Ticket_Key;
                } else {
                    //到期
                    $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=' . $token . '&type=jsapi';
                    $responseText = $this->getHttpResponseGET($url);
                    if ($responseText != '') {
                        $jsonTicket = json_decode($responseText);
                        if ((array_key_exists('ticket', $jsonTicket))) {
                            $jsonKey = $jsonTicket->ticket;
                            if ($jsonKey != '') {
                                $ticket = $jsonKey;
                                $xml->Ticket_Key = $jsonKey;//修改节点
                                $xml->Ticket_Time = date('Y-m-d H:i:s', time() + 7200);
                                $xml->asXML('XMLTicket.xml');
                            } else {
                                $ticket = 'no';
                            }
                        } else {
                            $ticket = 'no';
                        }
                    } else {
                        $ticket = 'no';
                    }
                }
            }
        }
        return $ticket;
    }

    /**时间戳
     * @return bool|string
     */
    protected function timeStamp()
    {
        return strtotime('now');
    }

    /**
     * 远程获取数据，GET模式
     * 注意：
     * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
     * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
     * @param $url 指定URL完整路径地址
     * @param $cacert_url 指定当前工作目录绝对路径
     * return 远程输出的数据
     */
    protected function getHttpResponseGET($url)
    {
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//SSL证书认证
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
        //curl_setopt($curl, CURLOPT_CAINFO, $cacert_url);//证书地址
        $responseText = curl_exec($curl);
        //var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
        curl_close($curl);
        return $responseText;
    }

    /**返回会员详细
     * @param $type
     * @param $name
     * @return string
     */
    protected function checkMemberInfo($name, $key)
    {
        $entMemberInfo = EntMemberInfo::select('MemNumber', 'UserName', 'States', 'MemEndTime', 'YourName', 'FilePath1')->where('DeleteMark', '1')->where('UserName', $name)->where('LoginKey', $key)->first();
        return $entMemberInfo;
    }

    /**
     * 合伙人中心
     */
    public function partneralert()
    {
        return view('test/partneralert');
    }

    public function indexPartner()
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        if (count($memberInfo) > 0) {
            $entMemberDRP = EntMemberDRP::select('FinishMoney', 'SalesMoney', 'DRPID','IsRebate','MemBalances')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', 1)->first();
        }
        /**
         * 7天的销售情况--开始
         */
        $timeMax = date('Y-m-d', time());
        $timeMin = date("Y-m-d", strtotime("-6 day"));
        $entPushMoneyLog = EntPushMoneyLog::select('AddDate')->where('MemNumber', $memberInfo->MemNumber)->whereDate('AddDate', '>=', $timeMin)->whereDate('AddDate', '<=', $timeMax)->get();
        $arrayWeekCount = '';
        for ($i = 1; $i < 8; $i++) {
            $arrayWeekCount[date("Y-m-d", strtotime(($i - 7) . " day"))] = 0;
        }
        if (count($entPushMoneyLog) > 0) {
            foreach ($entPushMoneyLog as $key) {
                $addDate = date('Y-m-d', strtotime($key->AddDate));
                if (array_key_exists($addDate, $arrayWeekCount)) {
                    $arrayWeekCount[$addDate] = $arrayWeekCount[$addDate] + 1;
                }
            }
        }
        /**
         * 7天的销售情况--结束
         */
        $entMemberDRPTwo = EntMemberDRP::select('DRPLevel')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', 1)->first();
        if (count($entMemberDRPTwo) > 0) {
            if ($entMemberDRPTwo->DRPLevel > 1) {
                return redirect('/partneralert.html');
            }
        } else {
            return redirect('/partneralert.html');
        }
        return view('partner.index', ['memberInfo' => $memberInfo, 'entMemberDRP' => $entMemberDRP, 'entPushMoneyLog' => $arrayWeekCount]);
    }

    /**
     * 我的书友--结束
     */
    public function bookfriend()
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        if (count($memberInfo) > 0) {
            $parentID = EntMemberDRP::select('DRPID')->where('MemNumber', $memberInfo->MemNumber)->first();
            if (count($parentID) > 0) {
                $entMemberDRP = DB::table('VW_WEB_memberdrp')->select('YourName', 'FilePath1', 'AddDate')->where('DeleteMark', 1)->where('ParentID', $parentID->DRPID)->orderBy('AddDate', 'desc')->get();
            }
        }
        $keyword = '';
        return view('partner.bookfriend', ['entMemberDRP' => $entMemberDRP, 'keyword' => $keyword]);
    }

    public function searchbookfriend($keyword = '')
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        if (count($memberInfo) > 0) {
            $parentID = EntMemberDRP::select('DRPID')->where('MemNumber', $memberInfo->MemNumber)->first();
            if ($keyword != '') {
                $entMemberDRP = DB::table('VW_WEB_memberdrp')->select('YourName', 'FilePath1', 'AddDate')
                    ->where('DeleteMark', '1')
                    ->where('ParentID', $parentID->DRPID)
                    ->where('YourName', 'like', '%' . $keyword . '%')
                    ->orderBy('AddDate', 'desc')
                    ->get();
            } else {

                if (count($parentID) > 0) {
                    $entMemberDRP = DB::table('VW_WEB_memberdrp')->select('YourName', 'FilePath1', 'AddDate')->where('DeleteMark', 1)->where('ParentID', $parentID->DRPID)->orderBy('AddDate', 'desc')->get();
                }
            }
        }
        return view('partner.bookfriend', ['entMemberDRP' => $entMemberDRP, 'keyword' => $keyword]);
    }

    public function searchbookfriendTwo($id = '')
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        $entMemberDRP = '';
        if (count($memberInfo) > 0) {
            $parentID = EntMemberDRP::select('DRPID')->where('MemNumber', $memberInfo->MemNumber)->first();
            if ($id != '') {
                if ($id == 1) {
                    $entMemberDRP = DB::table('VW_WEB_memberdrp')->select('YourName', 'FilePath1', 'AddDate')
                        ->where('DeleteMark', '1')
                        ->where('ParentID', $parentID->DRPID)
                        ->orderBy('AddDate', 'desc')
                        ->get();
                } else {
                    $entMemberDRP = DB::table('VW_WEB_memberdrp')->select('YourName', 'FilePath1', 'AddDate')
                        ->where('DeleteMark', '1')
                        ->where('ParentID', $parentID->DRPID)
                        ->orderBy('AddDate', 'desc')
                        ->get();
                }
            }
        }
        return view('partner.bookfriend', ['entMemberDRP' => $entMemberDRP]);
    }
    /**
     * 我的书友--开始
     */
    /**会员提点
     * @param string $memNumber
     */
    protected function pushMoneyLogStore($memNumber = '')
    {
        if ($memNumber != '') {
            $entMemberDRP = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID')->where('MemNumber', $memNumber)->first();
            if (count($entMemberDRP) > 0) {
                $parentID = $entMemberDRP->ParentID;
                if ($parentID > 0) {
                    $entMemberDRPTwo = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID', 'SalesMoney', 'FinishMoney', 'MemBalances', 'MemNumber', 'IsRebate')->where('DRPID', $parentID)->first();
                    if (count($entMemberDRPTwo) > 0) {
                        $parentIDTwo = $entMemberDRPTwo->ParentID;
                        if ($parentIDTwo == 0) {
                            //返点30%
                            DB::beginTransaction();
                            try {
                                $money = $this->scaleMoney * $this->scaleOne;
                                $toalMoney = $this->scaleMoney + $entMemberDRPTwo->FinishMoney;
                                //DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                $entPushMoneyLog = new EntPushMoneyLog();
                                $entPushMoneyLog->MemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLog->Scale = $this->scaleOne;
                                $entPushMoneyLog->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLog->PayMoney = $money;
                                $entPushMoneyLog->ToMemNumber = $memNumber;
                                $entPushMoneyLog->PushMoneyDesc = '发展新会员提点30%';
                                $entPushMoneyLog->DeleteMark = 1;
                                $entPushMoneyLog->MemberType = 1;
                                $entPushMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->save();
                                $k = 0;
                                if ($toalMoney >= $entMemberDRPTwo->SalesMoney) {
                                    if ($toalMoney == $entMemberDRPTwo->SalesMoney) {
                                        //返销售指标+销售业绩
                                        $k = 1;
                                    } else {
                                        if ($entMemberDRPTwo->FinishMoney > $entMemberDRPTwo->SalesMoney) {
                                            //提点+销售业绩
                                            $k = 2;
                                        } else {
                                            if ($entMemberDRPTwo->FinishMoney == $entMemberDRPTwo->SalesMoney) {
                                                $k = 2;
                                            } else {
                                                //提点+销售业绩
                                                $k = 3;
                                            }
                                        }

                                    }

                                } else {
                                    //销售业绩
                                    $k = 4;
                                }
                                switch ($k) {
                                    case 1:
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        }
                                        break;
                                    case 2:
                                        $memBalances = $money + $entMemberDRPTwo->MemBalances;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        break;
                                    case 3:
                                        $scaleMoneyTree = $toalMoney - $entMemberDRPTwo->SalesMoney;
                                        $moneyTree = $scaleMoneyTree * $this->scaleOne;
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        } else {
                                            $memBalances = $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        }
                                        break;
                                    case 4:
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                        break;
                                }
                                DB::commit();
                            } catch (Exception $e) {
                                DB::rollBack();
                            }

                        } else {
                            $entMemberDRPTree = EntMemberDRP::select('DRPID', 'DRPLevel', 'ParentID', 'IsRebate', 'SalesMoney', 'MemBalances', 'FinishMoney', 'MemNumber')->where('DRPID', $parentIDTwo)->first();
                            if (count($entMemberDRPTree)) {
                                //返点30%
                                $money = $this->scaleMoney * $this->scaleOne;
                                $toalMoney = $this->scaleMoney + $entMemberDRPTwo->FinishMoney;
                                // DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                $entPushMoneyLog = new EntPushMoneyLog();
                                $entPushMoneyLog->MemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLog->Scale = $this->scaleOne;
                                $entPushMoneyLog->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLog->PayMoney = $money;
                                $entPushMoneyLog->ToMemNumber = $memNumber;
                                $entPushMoneyLog->PushMoneyDesc = '发展新会员提点30%';
                                $entPushMoneyLog->DeleteMark = 1;
                                $entPushMoneyLog->MemberType = 1;
                                $entPushMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLog->save();
                                $j = 0;
                                if ($toalMoney >= $entMemberDRPTwo->SalesMoney) {
                                    if ($toalMoney == $entMemberDRPTwo->SalesMoney) {
                                        //返销售指标+销售业绩
                                        $j = 1;
                                    } else {
                                        if ($entMemberDRPTwo->FinishMoney > $entMemberDRPTwo->SalesMoney) {
                                            //提点+销售业绩
                                            $j = 2;
                                        } else {
                                            if ($entMemberDRPTwo->FinishMoney == $entMemberDRPTwo->SalesMoney) {
                                                $j = 2;
                                            } else {
                                                //提点+销售业绩
                                                $j = 3;
                                            }
                                        }
                                    }

                                } else {
                                    //销售业绩
                                    $j = 4;
                                }
                                switch ($j) {
                                    case 1:
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        }
                                        break;
                                    case 2:
                                        $memBalances = $money + $entMemberDRPTwo->MemBalances;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        break;
                                    case 3:
                                        $scaleMoneyTree = $toalMoney - $entMemberDRPTwo->SalesMoney;
                                        $moneyTree = $scaleMoneyTree * $this->scaleOne;
                                        if ($entMemberDRPTwo->IsRebate == 0) {
                                            $memBalances = $entMemberDRPTwo->SalesMoney + $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances, 'IsRebate' => 1]);
                                        } else {
                                            $memBalances = $entMemberDRPTwo->MemBalances + $moneyTree;
                                            DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney, 'MemBalances' => $memBalances]);
                                        }
                                        break;
                                    case 4:
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTwo->DRPID)->update(['FinishMoney' => $toalMoney]);
                                        break;
                                }
                                //返点5%
                                $moneyTwo = $this->scaleMoney * $this->scaleTwo;
                                $toalMoneyTwo = $moneyTwo + $entMemberDRPTree->FinishMoney;
                                if ($entMemberDRPTree->FinishMoney >= $entMemberDRPTree->SalesMoney) {
                                    if ($entMemberDRPTree->IsRebate == 0) {
                                        $memBalances = $entMemberDRPTree->SalesMoney + $entMemberDRPTree->MemBalances + $moneyTwo;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['MemBalances' => $memBalances, 'IsRebate' => 1]);
                                    } else {
                                        $memBalances = $entMemberDRPTree->MemBalances + $moneyTwo;
                                        DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['MemBalances' => $memBalances]);
                                    }
                                }
                                //DB::table('MemberDRP')->where('DRPID', $entMemberDRPTree->DRPID)->update(['FinishMoney' => $toalMoneyTwo]);
                                $entPushMoneyLogTwo = new EntPushMoneyLog();
                                $entPushMoneyLogTwo->MemNumber = $entMemberDRPTree->MemNumber;
                                $entPushMoneyLogTwo->Scale = $this->scaleTwo;
                                $entPushMoneyLogTwo->TotalMoney = $this->scaleMoney;
                                $entPushMoneyLogTwo->PayMoney = $moneyTwo;
                                $entPushMoneyLogTwo->ToMemNumber = $entMemberDRPTwo->MemNumber;
                                $entPushMoneyLogTwo->PushMoneyDesc = '下线合伙人发展新会员提点5%';
                                $entPushMoneyLogTwo->DeleteMark = 1;
                                $entPushMoneyLogTwo->MemberType = 1;
                                $entPushMoneyLogTwo->ReleaseDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTwo->AddDate = date('Y-m-d H:i:s', time());
                                $entPushMoneyLogTwo->save();
                            }
                        }
                    }
                }
            }
        }
    }

    /*
     * 佣金
     */
    public function commission()
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        if (count($memberInfo) > 0) {
            $entMemberDRP = EntMemberDRP::select('FinishMoney', 'SalesMoney', 'MemBalances','IsRebate', 'DRPID')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', 1)->first();
        }
        $entWithdrawMoneyLog = EntWithdrawMoneyLog::select('CardNo', 'States', 'WithdrawRemark', 'WithdrawMoney', 'AddDate')->where('MemNumber', $memberInfo->MemNumber)->orderBy('AddDate', 'desc')->get();
        $entPushMoneyLog = DB::table('vw_web_pushmoneylog')->select('PuMoID','MemNumber','Scale','IsFinish', 'TotalMoney', 'SalesMoney', 'PayMoney', 'MemberType', 'YourName', 'AddDate')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', '1')->orderBy('AddDate', 'desc')->get();
        $IsRebate=$entMemberDRP->IsRebate;
        $firstid = EntPushMoneyLog::select('PuMoID')->where('IsFinish', 1)->where('MemNumber', $memberInfo->MemNumber)->orderBy('AddDate', 'asc')->first();
        $id=0;
        if (count($firstid)>0){
            $id=$firstid->PuMoID;
        }
        return view('partner.commission', ['entMemberDRP' => $entMemberDRP, 'entWithdrawMoneyLog' => $entWithdrawMoneyLog, 'entPushMoneyLog' => $entPushMoneyLog,'IsRebate'=>$IsRebate,'id'=>$id]);
    }

    /*
     * 提现方式列表
     */
    public function bankcodelist()
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        $bankTypeList = $this->arrayBank;
        if (count($memberInfo) > 0) {
            $entPayCard = EntPayCard::select('PaCaID', 'CardNo', 'PayType', 'BankType')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', '1')->get();
        }
        return view('partner.bankcodelist', ['entPayCard' => $entPayCard, 'bankTypeList' => $bankTypeList]);
    }

    /*
     * 添加提现方式
     */
    public function bankcode()
    {
        $bankTypeList = $this->arrayBank;
        return view('partner.bankcode', ['bankTypeList' => $bankTypeList]);
    }

    public function bankcodeStore(Request $request)
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        if (count($memberInfo) > 0) {
            $entPayCard = new EntPayCard();
            $entPayCard->PayType = 1;
            $entPayCard->MemNumber = $memberInfo->MemNumber;
            $entPayCard->CardNo = trim($request->get('txtCode'));
            $entPayCard->BankType = trim($request->get('hiBankType'));
            $entPayCard->YourName = trim($request->get('txtCardName'));
            $entPayCard->DeleteMark = 1;
            $entPayCard->ReleaseDate = date('Y-m-d H:i:s', time());
            $entPayCard->AddDate = date('Y-m-d H:i:s', time());
            $entPayCard->save();
            if ($entPayCard) {
                return redirect('/partner/bankcodelist.html');
            }
        }
    }

    /*
     * 绑定支付宝账号
     */
    public function alipaycode()
    {
        return view('partner.alipaycode');
    }

    public function alipaycodeStore(Request $request)
    {
        $MName = Session::get('MName');
        $MKey = Session::get('MKey');
        $memberInfo = $this->checkMemberInfo($MName, $MKey);
        if (count($memberInfo) > 0) {
            $entPayCard = new EntPayCard();
            $entPayCard->PayType = 2;
            $entPayCard->MemNumber = $memberInfo->MemNumber;
            $entPayCard->CardNo = trim($request->get('txtCode'));
            $entPayCard->BankType = 0;
            $entPayCard->YourName = '';
            $entPayCard->DeleteMark = 1;
            $entPayCard->ReleaseDate = date('Y-m-d H:i:s', time());
            $entPayCard->AddDate = date('Y-m-d H:i:s', time());
            $entPayCard->save();
            if ($entPayCard) {
                return redirect('/partner/bankcodelist.html');
            }
        }
    }

    public function withdrawmoney($id)
    {
        //$bankName=$this->arrayBank[$id];
        // $paCaID
        if (is_numeric($id)) {
            $bankName = '';
            $memBalances = 0;
            $mobile = '';
            $mobilestr = '';
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            $id = $id;
            $memberInfo = $this->checkMemberInfo($MName, $MKey);
            if (count($memberInfo) > 0) {
                $entPayCard = EntPayCard::select('PayType', 'BankType', 'MemNumber', 'CardNo')->find($id);
                if (count($entPayCard) > 0) {
                    if ($memberInfo->MemNumber == $entPayCard->MemNumber) {
                        $entMemberDRP = EntMemberDRP::select('FinishMoney', 'SalesMoney', 'DRPID', 'MemBalances')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', 1)->first();
                        if ($entPayCard->PayType == 2) {
                            $bankName = '支付宝&nbsp;（尾号' . substr($entPayCard->CardNo, -4) . '）';
                        } else {
                            $bankName = $this->arrayBank[$entPayCard->BankType] . '&nbsp;（尾号' . substr($entPayCard->CardNo, -4) . '）';
                        }
                        $memBalances = $entMemberDRP->MemBalances;
                        $mobile = substr($memberInfo->UserName, 0, 3) . '*****' . substr($memberInfo->UserName, -3);
                        $mobilestr = $memberInfo->UserName;
                    }
                }
            }
        }
        return view('partner.withdrawmoney', ['bankName' => $bankName, 'memBalances' => $memBalances, 'mobile' => $mobile, 'mobilestr' => $mobilestr, 'id' => $id, 'address' => $this->address]);
    }

    /*
     * 发送短信 --开始
     */
    // 验证手机验证码
    public function addMobCode(Request $request)
    {
        $result = '';
        try {
            if ($request->ajax()) {
                $userimgcode = '';
                $usermobile = $request->json('mobile');
                if ($usermobile != '') {
                    $entMobileCodeTime = EntMobileCode::select('EndTime', 'ID')->where('Mobile', $usermobile)
                        ->where('States', 1)
                        ->orderBy('AddDate', 'desc')
                        ->first();
                    if (count($entMobileCodeTime) > 0) {
                        $nowtime = date('Y-m-d h:i:s', time());
                        $endtime = $entMobileCodeTime->EndTime;
                        if (strtotime($nowtime) < strtotime($endtime)) {
                            // 时间没有到
                            $result = '2';
                        } else {
                            $Code = $this->RandStr(5);
                            if ($usermobile != '' && $Code != '') {
                                $now = date('Y-m-d h:i:s', time());
                                $entMobileCode = new EntMobileCode();
                                $entMobileCode->States = 1;
                                $entMobileCode->Mobile = $usermobile;
                                $entMobileCode->Code = $Code;
                                $entMobileCode->EndTime = date("Y-m-d H:i:s", strtotime("+2minutes", strtotime($now)));
                                $entMobileCode->AddDate = date('Y-m-d H:i:s', time());
                                $entMobileCode->save();
                                if ($entMobileCode) {
                                    $coment = $this->getMobileCode($usermobile, $Code);
                                    DB::table('mobilecode')->where('ID', $entMobileCode->ID)->update(['msg' => $coment]);
                                    if ($coment != '') {
                                        $k = explode(',', $coment);
                                        $g = $k[0];
                                        if ($g == 0) {
                                            // 发送成功！
                                            $result = '3';
                                        } else {
                                            // 发送失败！
                                            $result = '4';
                                        }
                                    } else {
                                        $result = '4';
                                    }
                                }
                            } else {
                                // 短信发送失败
                                $result = '4';
                            }
                        }
                    } else {
                        $Code = $this->RandStr(5);
                        if ($usermobile != '' && $Code != '') {
                            $now = date('Y-m-d h:i:s', time());
                            $entMobileCode = new EntMobileCode();
                            $entMobileCode->States = 1;
                            $entMobileCode->Mobile = $usermobile;
                            $entMobileCode->Code = $Code;
                            $entMobileCode->EndTime = date("Y-m-d H:i:s", strtotime("+2minutes", strtotime($now)));
                            $entMobileCode->AddDate = date('Y-m-d H:i:s', time());
                            $entMobileCode->save();
                            if ($entMobileCode) {
                                $coment = $this->getMobileCode($usermobile, $Code);
                                DB::table('mobilecode')->where('ID', $entMobileCode->ID)->update(['msg' => $coment]);
                                if ($coment != '') {
                                    $k = explode(';', $coment);
                                    $g = $k[0];
                                    if ($g == 'OK') {
                                        // 发送成功！
                                        $result = '3';
                                    } else {
                                        // 发送失败！
                                        $result = '4';
                                    }
                                } else {
                                    $result = '4';
                                }
                            }
                        } else {
                            // 短信发送失败
                            $result = '4';
                        }
                    }
                }
            }
        } catch (Exception $e) {
            $result = '4';
        }
        return $result;
    }

    // 验证手机验证码
    public function checkMobCode(Request $request)
    {
        $result = '';
        try {
            $MName = Session::get('MName');
            $MKey = Session::get('MKey');
            $memberInfo = $this->checkMemberInfo($MName, $MKey);
            if (count($memberInfo) > 0) {
                if ($request->ajax()) {
                    $userimgcode = '';
                    $usermobcode = $request->json('mobcode');
                    $usermobile = $request->json('mobile');
                    $type = $request->json('type');
                    $price = $request->json('price');
                    $title = $request->json('title');
                    $expname = $request->json('expname');
                    $expnumber = $request->json('expnumber');
                    $mobileCode = EntMobileCode::select('ID')->where('Mobile', $usermobile)
                        ->where('States', 1)
                        ->where('Code', $usermobcode)
                        ->first();
                    if (count($mobileCode) > 0) {

                        //获取支付方式详细
                        $entPayCard = EntPayCard::select('PayType', 'CardNo', 'BankType', 'YourName', 'MemNumber')->find($type);
                        if (count($entPayCard) > 0) {
                            DB::beginTransaction();
                            try {
                                //获取合伙人详细
                                $entMemberDRP = EntMemberDRP::select('SalesMoney', 'FinishMoney', 'MemBalances')->where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', 1)->first();
                                if (count($entMemberDRP) > 0) {
                                    if ($entMemberDRP->FinishMoney >= $entMemberDRP->SalesMoney) {
                                        //抵扣合伙人金额
                                        $memBalances = $entMemberDRP->MemBalances - $price;
                                        if ($memBalances >= 0) {
                                            $entWithdrawMoneyLog = new EntWithdrawMoneyLog();
                                            $entWithdrawMoneyLog->States = 0;
                                            $entWithdrawMoneyLog->InvoiceTitle = $title;
                                            $entWithdrawMoneyLog->MemNumber = $memberInfo->MemNumber;
                                            if ($entPayCard->PayType == 2) {
                                                $entWithdrawMoneyLog->CardNo = $entPayCard->CardNo;
                                                $entWithdrawMoneyLog->BankName = '支付宝账号';
                                                $entWithdrawMoneyLog->YourName = '';
                                            } else {
                                                $entWithdrawMoneyLog->CardNo = $entPayCard->CardNo;
                                                $entWithdrawMoneyLog->BankName = $this->arrayBank[$entPayCard->BankType];
                                                $entWithdrawMoneyLog->YourName = $entPayCard->YourName;
                                            }
                                            $entWithdrawMoneyLog->WithdrawMoney = $price;
                                            $entWithdrawMoneyLog->ExpressName = $expname;
                                            $entWithdrawMoneyLog->ExpressNumber = $expnumber;
                                            $entWithdrawMoneyLog->DeleteMark = 1;
                                            $entWithdrawMoneyLog->ReleaseDate = date('Y-m-d H:i:s', time());
                                            $entWithdrawMoneyLog->AddDate = date('Y-m-d H:i:s', time());
                                            $entWithdrawMoneyLog->save();
                                            EntMemberDRP::where('MemNumber', $memberInfo->MemNumber)->where('DeleteMark', 1)->update(['MemBalances' => $memBalances]);
                                            EntMobileCode::where('Mobile', $usermobile)->where('States', 1)->delete();
                                            $result = '3';
                                        } else {
                                            $result = '7';
                                        }
                                    } else {
                                        $result = '7';
                                    }
                                }
                                DB::commit();
                            } catch (Exception $e) {
                                DB::rollBack();
                            }
                        }
                    } else {
                        // 您输入的手机验证码不正确
                        $result = '2';
                    }
                }
            }
        } catch (Exception $e) {
            $result = '4';
        }
        return $result;
    }

    //随机数字
    protected function RandStr($n)
    {
        $s = '';
        $str = "123567898"; // 输出字符集
        $len = strlen($str) - 1;
        for ($i = 0; $i < $n; $i++) {
            $s .= $str[rand(0, $len)];
        }
        return $s;
    }

    protected function getMobileCode($mobile = '', $code = '')
    {
        $msg = '校验码' . $code . '，您的老侯代读正在提交提现申请，请勿告诉别人哦！';
        $url = 'http://103.47.139.8/SHHL95/qxtinterface.aspx?phone=' . $mobile . '&message=' . iconv("UTF-8", "gb2312", $msg) . '&user=nanguash&pwd=laohou123';
        if (ini_get("allow_url_fopen") == "1") {
            $response = file_get_contents($url);
        } else {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_URL, $url);
            $response = curl_exec($ch);
            curl_close($ch);
        }

        // -------请求为空
        if (empty($response)) {
            $this->error->showError("50001");
        }
        return $response;
    }
    /*
     * 发送短信 --结束
     */
}